import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

from sunPro.items import SunproItem
from sunPro.items import DetailItem

class RunSpider(CrawlSpider):
    name = 'run'
    # allowed_domains = ['www.xxx.com']
    start_urls = ['http://wz.sun0769.com/political/index/politicsNewest']

    #　链接提取器
    link = LinkExtractor(allow=r'id=1&page=\d+')
    # http://wz.sun0769.com/html/question/201907/421001.html
    link_detail = LinkExtractor(allow=r'question/\d+\.shtml')
    rules = (
        # 规则解析器:将链接提取到的链接进行指定规则(callback)的解析操作
        Rule(link, callback='parse_item', follow=True),
        # follow=True：可以将链接提取器继续作用到 提取到的链接所对应的页面中
        Rule(link_detail, callback='parse_detail')
    )

    # 以下两个解析方法中是不可以实现请求传参！
    # 将两个解析方法解析的数据存储到同一个item中，可以依次存储到两个item中
    # 解析新闻编号和新闻的标题
    def parse_item(self, response):
        tr_list = response.xpath('//*[@id="morelist"]/div/table[2]//tr/td/table//tr')
        for tr in tr_list:
            new_num = tr.xpath('./td[1]/text()').extract_first()
            title = tr.xpath('./td[2]/a[2]/@title').extract_first()
            item = SunproItem()
            item['title'] = title
            item['new_num'] = new_num

            yield item

    # 解析新闻内容和新闻编号
    def parse_detail(self, response):
        new_id = response.xpath('/html/body/div[9]/table[1]/tbody/tr/td[2]/span[2]/text()').extract_first()
        new_content = response.xpath('/html/body/div[9]/table[2]/tbody/tr[1]//text()')
        new_content = ''.join(new_content)

        item = DetailItem()
        item['content'] = new_content
        item['new_id'] = new_id

